<template>
  <view>
    <u-form :model="model" :rules="rules" labelPosition="top" ref="form" labelWidth="auto" :labelStyle="{
      fontSize: '14px',
      color: '#B2B2B2',
      lineHight: '20px'
    }">
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="标题" prop="title" required>
          <u--input v-model="model.title" :maxlength="100" placeholder="请输入标题"></u--input>
        </u-form-item>
				<u-form-item label="类别" prop="noticeCategory" required>
					<h-dict-select
						style="width: 100%" 
						v-model="model.noticeCategory" 
						placeholder="请选择类别" 
						dictName="notice_category"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
					></h-dict-select>
				</u-form-item>
				<u-form-item label="发文密级" prop="intensiveType" required>
					<h-dict-select
						style="width: 100%" 
						v-model="model.intensiveType" 
						placeholder="请选择发文密级" 
						dictName="document_intensive_type"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						@input="handleIntensiveInput"
					></h-dict-select>
				</u-form-item>
        <u-form-item label="发布人" required>
					<u--input :value="model.handlerId_dictText || userInfo.realname" disabled placeholder="请输入"></u--input>
        </u-form-item>
        <u-form-item label="内容" prop="content">
          <springEditor v-model="model.content" placeholder="请输入内容"></springEditor>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">
            提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！
          </view>
          <h-upload-file v-model="model.attachments" :isIcon="false" fileType=".pdf, .PDF"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>
			<view class="basic-style">
			  <view class="basic-title basic-border">选择接收人</view>
			  <view class="py-1 space-y-1" style="width: 100%">
					<u-button size="small" type="primary" @click="pickShow = true">{{selectedPersonNum?'我已选择' : '我未选择'}}</u-button>
			  </view>
			</view>
			<!-- <h-editor-input
				 v-model="model.content"
			></h-editor-input> -->
			<view class="space-x-1 px-1 btn_position">
			  <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
			  <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx"></view>
    </u-form>

    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
		<u-picker :show="pickShow" :closeOnClickOverlay="true" ref="uPicker" :columns="columns" @confirm="confirm" @cancel="pickShow = false" @close="pickShow = false"></u-picker>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import http from '@/utils/request'
import fileList from '@/pages/synergy/components/fileList.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import springEditor from "@/components/spring-spring-editor/editor.vue"
export default {
  name: 'noticeAnnounceList',
  components: { fileList, ProcessNodeConfiguration, springEditor },
  data() {
    return {
      loading: false,
      info: false,
			moment,
      model: {
        title: '',
        noticeCategory: '',
				intensiveType: '', // 密级
        handlerId: '',
        handlerId_dictText: '',
				content: '',
				attachments: '',
      },
      
      rules: {
        title: [
          { required: true, message: '请输入标题!', trigger: 'blur' },
        ],
        noticeCategory: [
          { required: true, message: '请选择类别!', trigger: 'change' },
        ],
				intensiveType: [
          { required: true, message: '请选择发文密级!', trigger: 'change' },
        ],
      },
			dictOptions: {},
      isSubmit: false,
      //代码生成后需手动设置流程编码
      flowCode: 'onl_erp_publish_notice',
      formUrl: "/erp/docManage/modules/noticeForm",
      formUrlMobile: "/pages/synergy/noticeAnnounceList",
      processId: '',
			beanName: 'erpPublishNoticeServiceImpl',
			pickShow: false
    }
  },
  onLoad({ id }) {
    this.id = id || ''
		if (id) {
			// 编辑
			this.edit(id)
			this.getSelectUsers(id)
		} else {
			// 添加
			this.add()
		}
  },
  computed: {
    ...mapState(['userInfo']),
		// 监听数据
		selectedPersonNum () {
			if (this.$store.state.selectPerson && this.$store.state.selectPerson.length) {
				return this.$store.state.selectPerson.length
			} else {
				return 0
			}
		},
		columns () {
			// 根据密级判断展示选择
			if (!this.model.intensiveType || this.model.intensiveType == 'ordinary') {
				// 普通
				return  [
					[{
						text: '公司架构',
						id: '1'
					},
					{
						text: '个人小组',
						id: 'personal'
					},{
						text: '公用小组',
						id: 'public'
					}]
				]
			} else {
				return  [
					[{
						text: '公用小组',
						id: 'public'
					}]
				]
			}
			
		}
  },
  methods: {
		// 选择密级
		handleIntensiveInput () {
			// 清空选择
			this.$store.state.selectPerson = []
		},
		confirm(e) {
			const value = e.value[0]
			if(value.id=='1'){
				this.selectPerson()
			} else {
				this.selectContact(e)
			}
			this.pickShow = false
		},
		// 用户信息
		// 编辑
		async edit(id) {
			// 获取详情
			// this.getDetail(id)
			http.get('/api/erp/publishNotice/queryPageById', { id }).then(res => {
				if (res.success) {
					this.model = res.result.records[0]
				}
			})
		},
		// 获取选中的接收人
		async getSelectUsers(id){
			let params = {
					noticeId: id,
					pageNo:1,
					pageSize:-1,
					empId: uni.getStorageSync('userInfo').empId
				}
				let res = await http.get('/api/erp/publishNotice/findEmpUserSelect',params)
				if(res.success){
					this.$store.state.selectPerson = res.result.records || []
				}else{
					this.$store.state.selectPerson = []
				}
		},
		// 点击新增
		add () {
			
		},
		selectPerson(){
			uni.navigateTo({
				url:'/pages/docManage/selectReceiver'
			})
		},
		selectContact(e){
			uni.navigateTo({
				url:`/pages/docManage/selectContactGroup?intensiveType=${this.model.intensiveType}&groupType=${e.value[0].id}`
			})
		},
    validateForm() {
			return this.$refs.form.validate().then(async () => {
			  if (!this.$store.state.selectPerson.length) {
			    this.$u.toast('请选择接收人！')
			    return Promise.reject('请选择接收人！')
			  }
			  return Promise.resolve()
			})
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
				let selectEmpList = await JSON.parse(JSON.stringify(this.$store.state.selectPerson))
				
				selectEmpList = await selectEmpList.map(rr=>{
					return {
						empId: rr.empId,
						empDepartIds: rr.departId,
						username: rr.username,
						realname: rr.realname,
					}
				})
        var response = await ''
        if (this.id) {
        	response = await  http.put('/api/erp/publishNotice/edit', {
        		...this.model,
        		selectEmpList
        	})
        } else {
        	response = await  http.post('/api/erp/publishNotice/add', {
        		...this.model,
        		selectEmpList
        	})
        }
        uni.showToast({
          title: response.message,
          icon: 'none',
        })
        if (response.success) {
          // 获取流程列表
          if (this.model.id) {
            this.getProcessList(this.model.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result.id)
            }

          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            }
          })
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
			await this.validateForm()
      this.isSubmit = true
      try {
        this.loading = true
				let selectEmpList = await JSON.parse(JSON.stringify(this.$store.state.selectPerson))
				selectEmpList = await selectEmpList.map(rr=>{
					return {
						empId: rr.empId,
						empDepartIds: rr.departId,
						username: rr.username,
						realname: rr.realname,
					}
				})
        var response = await ''
				if (this.id) {
					response = await  http.put('/api/erp/publishNotice/edit', {
						...this.model,
						selectEmpList
					})
				} else {
					response = await  http.post('/api/erp/publishNotice/add', {
						...this.model,
						selectEmpList
					})
				}
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home'
                })
              }

            }
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home'
            })
          }

        }
      })
    }
  },
}
</script>

<style scoped lang="scss">
	@import url('@/assets/inputStyle.scss');
</style>
